//
//  BTETools.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//


import Security
import AppTrackingTransparency
import AdSupport
import UIKit

class BTEDeviceIdentifierManager: NSObject {
    
    static let shared = BTEDeviceIdentifierManager()
    
    fileprivate let server = BTEUploadToolNetServer()
    
    private override init() {}
    
    private enum KeychainConstants {
        static let account = "devicefeonfew"
        static let service = "com.infomationdectice.few"
    }

    // MARK: - Public API
    
    /// 获取 IDFA（广告标识符）
    func advertisingID() -> String {
        return ASIdentifierManager.shared().advertisingIdentifier.uuidString
    }
    
    /// 获取 IDFV（供应商标识符）从钥匙串
    func vendorID() -> String {
        if let stored = BTEDeviceIdentifierManager.loadVendorIDFromKeychain(),
           stored.count > 0 {
            return stored
        } else {
            return UIDevice.current.identifierForVendor?.uuidString ?? ""
        }
    }
    
    /// 请求广告跟踪权限
    func requestTrackingAuthorizationIfNeeded(completion: @escaping (Bool) -> Void) {
        ATTrackingManager.requestTrackingAuthorization { status in
            completion(status == .authorized)
        }
    }

    // MARK: - Keychain Public Access
    
    /// 从钥匙串加载供应商标识符
    static func loadVendorIDFromKeychain() -> String? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: KeychainConstants.account,
            kSecAttrService as String: KeychainConstants.service,
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        
        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        
        guard status == errSecSuccess,
              let data = result as? Data else {
            return nil
        }
        return String(data: data, encoding: .utf8)
    }
    
    /// 判断是否已存储供应商标识符
    static func isVendorIDStored() -> Bool {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: KeychainConstants.account,
            kSecAttrService as String: KeychainConstants.service,
            kSecReturnData as String: false,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        return SecItemCopyMatching(query as CFDictionary, nil) == errSecSuccess
    }

    // MARK: - Keychain Private Storage
    
    /// 如果未存储，则保存供应商标识符
    static func storeVendorIDIfNeeded() {
        guard let identifier = UIDevice.current.identifierForVendor?.uuidString,
              let data = identifier.data(using: .utf8),
              !isVendorIDStored() else {
            return
        }
        saveVendorIDToKeychain(data)
    }
    
    /// 保存供应商标识符到钥匙串
    private static func saveVendorIDToKeychain(_ data: Data) {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: KeychainConstants.account,
            kSecAttrService as String: KeychainConstants.service,
            kSecValueData as String: data,
            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
        ]
        SecItemAdd(query as CFDictionary, nil)
    }
    
    func uploadIDVA(){
        let datas = ["augh":BTEDeviceIdentifierManager.shared.vendorID(),
                     "tailback":BTEDeviceIdentifierManager.shared.advertisingID()]
        server.dinarzade(data: datas) { resul in
            switch resul {
            case .success(let success):
                print("上传google成功")
                break
            case .failure(let failure):
                print("上传google失败")
                break
            }
        }
    }
}
